package nio.buffer;

import java.nio.ByteBuffer;
import java.nio.InvalidMarkException;

public class Rewind {

    public static void main(String[] args) {

        byte[] byteArray = new byte[] { 1, 2, 3, 4, 5 };
        ByteBuffer byteBuffer = ByteBuffer.wrap(byteArray);
        System.out.println("capacity=" + byteBuffer.capacity()
                + " limit=" + byteBuffer.limit()
                + " position=" + byteBuffer.position()); // capacity=5 limit=5 position=0

        byteBuffer.position(1);
        byteBuffer.limit(3);
        byteBuffer.mark();
        System.out.println(" capacity=" + byteBuffer. capacity()
                + " limit=" + byteBuffer. limit()
                + " position=" + byteBuffer. position()); // capacity=5 limit=3 position=1

        byteBuffer.rewind();
        System.out.println(" capacity=" + byteBuffer. capacity()
                + " limit=" + byteBuffer. limit()
                + " position=" + byteBuffer. position()); // capacity=5 limit=3 position=0

        try {
            // rewind()之后，mark < position，mark被丢弃，mark被丢弃的情况下reset()报错
            byteBuffer.reset();
        } catch (InvalidMarkException e) {
            e.printStackTrace();
        }

    }

}
